﻿using AutoMapper;
using HamcoWcs.Contract;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using System.Linq;

namespace HamcoWcs.Service.Common
{
    [AutoInject(typeof(IDbMsgService), InjectType.Scope)]
    public class DbMsgService : ScopeServiceBase, IDbMsgService
    {
        private readonly IPconBaseService _pconBaseService;

        public DbMsgService(WcsDbContext wcsDbContext, IMapper mapper, IPconBaseService pconBaseService) : base(wcsDbContext, mapper)
        {
            _pconBaseService = pconBaseService;

        }
        public void IsRepeated(PconDto pconDto, PconSendMsg pconSendMsg)
        {
            //var plc = _pconBaseService.GetPconPlc(pconDto.PlcName);
            var deviceMsgQueueDto = new DeviceMsgQueueDto(pconDto, pconSendMsg);
            var msg = _wcsDbContext.DeviceMsgQueues
                                   .AsQueryable()
                                   .Where(x => x.StartPoint == deviceMsgQueueDto.StartPoint)
                                   .Where(x => x.PlcName == deviceMsgQueueDto.PlcName)
                                   .Where(x => x.DeviceName == deviceMsgQueueDto.DeviceName)
                                   .Where(x => x.MsgValue == deviceMsgQueueDto.MsgValue)
                                   .OrderByDescending(x => x.Id)
                                   .FirstOrDefault();

            if (msg == null)
            {
                var deviceMsg = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                _wcsDbContext.DeviceMsgQueues.Add(deviceMsg);
            }
        }
    }
}
